package com.yzion.baselib.http.lifecycle

import androidx.lifecycle.*
import com.blankj.utilcode.util.ThreadUtils
import retrofit2.Call

open class CallLifecycleObserver(
    val lifecycle: Lifecycle,
    val call: Call<*>
) : DefaultLifecycleObserver {

    //在界面销毁时取消请求中的接口
    override fun onDestroy(owner: LifecycleOwner) {
        if (call.isCanceled.not()) {
            call.cancel()
        }
        removeObserver()
    }

    init {
        ThreadUtils.runOnUiThread {
            lifecycle.addObserver(this)
        }
    }

    open fun removeObserver() {
        ThreadUtils.runOnUiThread {
            lifecycle.removeObserver(this)
            callLifecycleObserverMap.remove(call)
        }
    }

}